<?php

namespace App\HttpController;


use App\Common\WX\WxApp;
use App\Model\t_wx_user;
use Carbon\Carbon;
use XWX\Common\H;

class ControllerWxApp extends ControllerBase
{
    function getUserID()
    {
        return $this->funcGetHeader('wxuserid');
    }

    function getOpenid()
    {
        return $this->funcGetWxUser()->wxuser_openid;
    }


    function funcGetWxApp()
    {
        $app = $this->context()->get(__METHOD__);
        if ($app === null)
        {
            $app = WxApp::funcIns($this->funcGetX__config());
            $this->context()->set(__METHOD__, $app);
        }

        return $app;
    }

    /**
     * @return t_wx_user
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    function funcGetWxUser()
    {
        $entity = $this->context()->get(__METHOD__);
        if ($entity === null)
        {
            $entity = t_wx_user::funcLoad($this->db(), $this->getUserID());
            $this->context()->set(__METHOD__, $entity);
        }

        return $entity;
    }


    protected function onRequest(?string $action): ?bool
    {
        $this->funcSetX($this->funcGetHeader('x'));
        if (H::funcStrIsNullOrEmpty($this->funcGetX()))
        {
            $this->funcWriteErr(-511, '访问凭证过期[x]');
            return false;
        }

        //验证
        $timestamp = $this->funcGetHeader('t');
        $token = $this->funcGetHeader('token');

        $sign_x = $this->funcGetWxApp()->funcGetSign($this->getUserID(), $timestamp);
        if ($sign_x !== $token)
        {
            $this->funcWriteErr(-123456, "token无效", ['sign' => $sign_x, 'token' => $token]);
            return false;
        }

        //判断时间
//        $t = Carbon::createFromTimestamp($timestamp);
//        $ts_m = H::now()->diffInHours($t);
//        if ($ts_m > 6)
//        {
//            $this->funcWriteErr(-512, '访问凭证过期，请回首页');
//            return false;
//        }


        return parent::onRequest($action);
    }
}